// pages/nome/nome.js
// 名片组内的名片
const nomeCards = require("../../mock/data/nome");
const utils = require("../../utils/util.js");

Page({
  ...utils.defaultShare,
  data: {
    chunkId: "",
    list: [],
    menuShow: false
  },
  onLoad: function (options) {
    console.log("options", options);
    this.setData({
      chunkId: options.chunkId || ''
    });
  },
  onShow: function () {
    this.getChunksItemList();
  },

  toggleSelect(event) {
    const _index = event.currentTarget.dataset.index;
    let list = [].concat(this.data.list);
    let checkAll = true;
    list.map((item, index) => {
      if (index == _index) {
        item.checked = !item.checked
      }
      if (!item.checked) {
        checkAll = false
      }
    })
    this.setData({ list, checkAll })
  },
  toggleSelectAll() {
    let list = [].concat(this.data.list);
    list.map((item, index) => {
      item.checked = !this.data.checkAll
    })
    this.setData({
      list,
      checkAll: !this.data.checkAll
    })
  },
  getChunksItemList() {
    utils
      .ajax("/v1/bcs/queryUserCardHolderGroupDetails.do", {
        groupId: this.data.chunkId
      })
      .then(res => {
        if (res.code === "000000") {
          this.setData({
            list: res.data.details || []
          });
        } else {
          console.log(res.message || "获取名片组详情列表失败");
          utils.message(res.message || "获取名片组详情列表失败");
        }
      })
      .catch(res => {
        utils.message(res.message || "网络错误");
      });

  },
  showDetail(event) {
    console.log(event)
    const detail = event.currentTarget.dataset.item;
    let url = '/pages/preview/preview?' + utils.serializeUrl(detail);
    wx.navigateTo({
      url
    })
  },
  hideMenu() {
    this.setData({
      menuShow: false
    })
  },
  showMenu() {
    this.setData({
      menuShow: true
    })
  },
  deleteCard() {
    // 从分组中删除该名片
    const holderIds = this.data.list.filter(item => {
      return !!item.checked
    }).map(item => {
      return item.holderId
    });
    const list = this.data.list.filter(item => {
      return !item.checked
    })
    utils
      .ajax("/v1/bcs/delFromUserCardHolderGroup.do", {
        groupId: this.data.chunkId,
        holderIds
      })
      .then(res => {
        if (res.code === "000000") {
          utils.message("移除成功");
          this.setData({
            list,
            menuShow: false
          }, ()=>{
            wx.navigateBack({
              delta: 1
            })
          })
        } else {
          console.log(res.message || "移除名片失败");
          utils.message(res.message || "移除名片失败");
        }
      })
      .catch(res => {
        utils.message(res.message || "网络错误");
      });
  }
});
